package com.yfp.operation.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * @Description: 生产二维码图片并打包
 * 
 * @CreateDate: 2024/7/22 20:44
 * @UpdateUser: 
 * @UpdateDate: 2024/7/22 20:44
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
public class QRCodeAndZipUtils {
    private static final int QR_CODE_SIZE = 200;

    public static List<Path> qrCodeAndZip(List<String> qrContents) throws WriterException, IOException {
        List<Path> filePaths = new ArrayList<>();
        for (String content : qrContents) {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE);
            Path path = FileSystems.getDefault().getPath(content.substring(content.indexOf("exportId=")+9)+".png");
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
            System.out.println("二维码已生成：" + path);
            filePaths.add(path);
        }
        return filePaths;
    }

    /**
     * 生成二维码并压缩包
     * @param destZipFile
     * @param qrContents
     * @throws IOException
     * @throws WriterException
     */
    public static void addFilesToZip(String destZipFile, List<String> qrContents) throws IOException, WriterException {
        FileOutputStream fos = new FileOutputStream(destZipFile);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        List<Path> paths = qrCodeAndZip(qrContents);
        for (Path path : paths) {
            File fileToZip = path.toFile();
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }
            fis.close();
            fileToZip.delete();
        }
        zipOut.close();
        fos.close();
    }
}
